<script setup>
import {onMounted, ref, watch, nextTick} from 'vue'
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import {globalStore} from "@/assets/store-index.js";

const gs = globalStore()

const bookList = ref([]);
const infoShow = ref(false);
const infoForm = ref({})
// 用于存储所有已选择的图书数据（跨页面）
const selectedBooks = ref(new Map())
// 表格引用
const tableRef = ref()
// 全选状态（跨页面）
const isSelectAll = ref(false)

const remove = (id) => {
  ElMessageBox.confirm('确定要删除这条图书记录吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    distinguishCancelAndClose: true,
  }).then(() => {
    axios.post("/book/remove", {id: id}).then(response => {
      listInfo();
      ElMessage.success(response.message);
    }).catch(error => {
      ElMessage.error(error)
    })
  }).catch(() => {
    // 用户取消操作
  });
}

// 批量删除
const removeBatch = () => {
  if (selectedBooks.value.size === 0 && !isSelectAll.value) {
    ElMessage.warning("请至少选择一条记录");
    return;
  }

  const message = isSelectAll.value
      ? '确定要删除全部图书记录吗？'
      : `确定要删除选中的 ${selectedBooks.value.size} 条图书记录吗？`;

  ElMessageBox.confirm(message, '批量删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    distinguishCancelAndClose: true,
  }).then(() => {
    if (isSelectAll.value) {
      // 删除全部记录
      axios.post("/book/removeAll").then(response => {
        listInfo();
        ElMessage.success(response.message);
        selectedBooks.value.clear();
        isSelectAll.value = false;
      }).catch(error => {
        ElMessage.error(error);
      });
    } else {
      // 删除选中的记录
      const ids = Array.from(selectedBooks.value.keys());
      axios.post("/book/removeBatch", ids).then(response => {
        listInfo();
        ElMessage.success(response.message);
        selectedBooks.value.clear();
      }).catch(error => {
        ElMessage.error(error);
      });
    }
  }).catch(() => {
    // 用户取消操作
  });
}

// 全选/取消全选
const toggleSelectAll = () => {
  if (isSelectAll.value) {
    // 取消全选
    selectedBooks.value.clear();
    isSelectAll.value = false;
    // 清除表格选中状态
    nextTick(() => {
      tableRef.value?.clearSelection();
    });
    ElMessage.success("已取消全选");
  } else {
    // 执行全选
    selectedBooks.value.clear();
    isSelectAll.value = true;
    // 选中当前页面所有项
    nextTick(() => {
      bookList.value.forEach(book => {
        tableRef.value?.toggleRowSelection(book, true);
      });
    });
    ElMessage.success("已全选");
  }
}

const openInfo = () => {
  infoForm.value = {}
  infoShow.value = true
}

const save = () => {
  const info = {...infoForm.value}
  axios.post("/book/save", info).then(response => {
    listInfo();
    ElMessage.success(response.message)
    infoShow.value = false
  }).catch(error => {
    ElMessage.error(error)
  })
}

const openEdit = (id) => {
  axios.post("/book/info", {id: id}).then(response => {
    const info = response.data;
    infoForm.value = {...info}
    infoShow.value = true;
  }).catch(error => {
    ElMessage.error(error)
  })
}

const requestBean = ref({pageNum: 1, pageSize: 5, total: 10, orderBy: 'created_time desc', params: {}})

const listInfo = () => {
  const token = gs.token;
  axios.post("/book/list", {...requestBean.value}).then(response => {
    const pageInfo = response.data;
    bookList.value = pageInfo.list;
    requestBean.value.total = pageInfo.total;

    // 更新当前页面的选中状态
    updateCurrentPageSelection();
  }).catch(error => {
    ElMessage.error(error)
  })
}

// 更新当前页面的选中状态
const updateCurrentPageSelection = () => {
  nextTick(() => {
    if (isSelectAll.value) {
      // 如果是全选状态，选中当前页面所有项
      bookList.value.forEach(book => {
        tableRef.value?.toggleRowSelection(book, true);
      });
    } else {
      // 根据selectedBooks中的数据更新表格选中状态
      bookList.value.forEach(book => {
        if (selectedBooks.value.has(book.id)) {
          tableRef.value?.toggleRowSelection(book, true);
        } else {
          tableRef.value?.toggleRowSelection(book, false);
        }
      });
    }
  });
}

const sortChange = (sort) => {
  const order = sort.order === 'ascending' ? 'asc' : 'desc';
  const prop = sort.order ? sort.prop : 'created_time';
  requestBean.value.orderBy = `${prop} ${order}`;
  listInfo();
}

const uploadImage = (options) => {
  const file = options.file;
  const formData = new FormData();
  formData.append("file", file);

  axios.postForm("/file/upload", formData).then(response => {
    infoForm.value.surface = response.data;
    ElMessage.success("图片上传成功");
  }).catch(error => {
    ElMessage.error(error)
  })
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  // 如果是全选状态，忽略单个选择操作
  if (isSelectAll.value) {
    return;
  }

  // 清空之前的选择
  selectedBooks.value.clear();

  // 添加新选中的项
  selection.forEach(book => {
    selectedBooks.value.set(book.id, book);
  });
}

// 处理分页变化
const handlePageChange = (newPage) => {
  requestBean.value.pageNum = newPage;
  listInfo();
}

// 预加载
onMounted(() => {
  listInfo();
})

// 监听页面数据变化，更新选中状态
watch(bookList, updateCurrentPageSelection);
</script>

<template>
  <div style="display: flex; justify-content: space-between;align-items: center">
    <div>
      <el-button type="primary" @click="openInfo" style="margin-bottom: .5rem">添加图书</el-button>
      <el-button type="danger" @click="removeBatch"
                 style="margin-bottom: .5rem; margin-left: 10px">
        批量删除 ({{ isSelectAll ? '全部' : selectedBooks.size }})
      </el-button>
      <el-button @click="toggleSelectAll" style="margin-bottom: .5rem; margin-left: 10px">
        {{ isSelectAll ? '取消全选' : '全选' }}
      </el-button>
    </div>
    <div style="display: flex;align-items: center;gap: 10px; ">
      <el-input v-model="requestBean.params.title" placeholder="请输入书名"
                style="width: 140px !important;display: block" clearable/>
      <el-input v-model="requestBean.params.author" placeholder="请输入作者"
                style="width: 140px !important;display: block" clearable/>
      <el-button type="primary" @click="listInfo">查询</el-button>
    </div>
  </div>

  <el-table
      ref="tableRef"
      :data="bookList"
      border
      stripe
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
      :row-key="row => row.id"
  >
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column prop="id" label="编号" width="280"/>
    <el-table-column prop="surface" label="封面">
      <template #default="props">
        <img :src="props.row.surface" style="width: 80px; height: 80px; border-radius: 5%"/>
      </template>
    </el-table-column>
    <el-table-column prop="title" label="书名" width="180"/>
    <el-table-column prop="author" label="作者" width="180"/>
    <el-table-column prop="introduction" label="简介"/>
    <el-table-column label="操作" width="180">
      <template #default="props">
        <el-button type="primary" size="small" @click="openEdit(props.row.id)">编辑</el-button>
        <el-button type="danger" size="small" @click="remove(props.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div>
    <el-pagination
        layout="prev, pager, next"
        :total="requestBean.total"
        :page-size="requestBean.pageSize"
        v-model:current-page="requestBean.pageNum"
        @current-change="handlePageChange"/>
  </div>

  <div>
    <el-dialog v-model="infoShow" title="图书详情" width="500">
      <el-form :model="infoForm">
        <el-form-item label="封面" :label-width="60">
          <el-upload class="avatar-uploader" :show-file-list="false" :http-request="uploadImage"
                     accept="image/png,image/jpeg,image/webp">
            <img v-if="infoForm.surface" :src="infoForm.surface" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="书名" :label-width="60">
          <el-input v-model="infoForm.title"/>
        </el-form-item>
        <el-form-item label="作者" :label-width="60">
          <el-input v-model="infoForm.author"/>
        </el-form-item>
        <el-form-item label="简介" :label-width="60">
          <el-input v-model="infoForm.introduction" type="textarea"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button @click="infoShow = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>
